package com.rural.bus;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.rural.bus.adapter.NearPoiAdapter;
import com.rural.bus.model.MyPoiInfo;
import com.rural.bus.view.SearchAddressPop;
import com.rural.bus.view.SearchAddressPop.SearchCallBack;

public class SearchAddressActivity extends BaseActivity implements
		OnItemClickListener, OnClickListener{

	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private ListView listview;
	private LinearLayout ll_search;
	private ImageView iv_icon_address;
	private TextView tv_search_history;

	private NearPoiAdapter mNearPoiAdapter;
	private List<MyPoiInfo> lists = new ArrayList<MyPoiInfo>();

	private LocationClient mLocationClient = null;
	private BDLocationListener myListener = new MyLocationListener();

	private boolean isClickMoving = false;
	private MyPoiInfo myPoiInfo;
	private String city="";
	private SearchAddressPop searchAddressPop;
	private String source = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 在使用SDK各组件之前初始化context信息，传入ApplicationContext
		// 注意该方法要再setContentView方法之前实现
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.activity_search_address);
		source = getIntent().getStringExtra("source");
		
		initView();
		setListeners();
		initData();
	}

	@Override
	protected void initView() {
		if("end".equals(source)){
			mBtMiddle.setText("下车地址");
		}else{
			mBtMiddle.setText("上车地址");
		}
		mBtMiddle.setVisibility(View.VISIBLE);
		mImgLeft.setVisibility(View.VISIBLE);
		mImgLeft.setBackgroundResource(R.drawable.back_bg_selector);
		mImgLeft.setOnClickListener(this);
		
		ll_search = (LinearLayout) findViewById(R.id.ll_search);
		ll_search.setOnClickListener(this);
		iv_icon_address = (ImageView) findViewById(R.id.iv_icon_address);
		if("end".equals(source)){
			iv_icon_address.setImageResource(R.drawable.icon_poi_end_address);
		}else{
			iv_icon_address.setImageResource(R.drawable.icon_poi_start_address);
		}
		tv_search_history = (TextView) findViewById(R.id.tv_search_history);
		tv_search_history.setText("搜索");
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();

		mBaiduMap.setMyLocationEnabled(true);
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
				MyLocationConfiguration.LocationMode.NORMAL, true, null));
		mBaiduMap.setOnMapStatusChangeListener(changeListener);

		listview = (ListView) findViewById(R.id.listview);
		listview.setOnItemClickListener(this);
		mNearPoiAdapter = new NearPoiAdapter(this, lists);
		listview.setAdapter(mNearPoiAdapter);

		mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
		mLocationClient.registerLocationListener(myListener); // 注册监听函数
		initLocation();
	}


	@Override
	protected void initData() {

	}

	@Override
	protected void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView.onResume()，实现地图生命周期管理
		mMapView.onResume();
		mLocationClient.start();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView.onPause()，实现地图生命周期管理
		mMapView.onPause();
		mLocationClient.stop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mMapView.onDestroy();
	}

	private void initLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
		int span = 1000;
		option.setScanSpan(1000);
		// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);// 可选，默认false,设置是否使用gps
		option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
		option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
		option.setIsNeedLocationPoiList(true);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
		option.setIgnoreKillProcess(false);// 可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
		option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
		option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		mLocationClient.setLocOption(option);
	}

	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			Log.d("rural", location.toString());
			if (location != null) {
				updateMapLocation(location.getLatitude(),
						location.getLongitude());
				city = location.getCity();
			}

			List<Poi> list = location.getPoiList();// POI数据
			if (list != null) {
				lists.clear();
				for (int i = 0; i < list.size(); i++) {
					Poi poi = list.get(i);
					MyPoiInfo myPoi = new MyPoiInfo(location.getLatitude(),
							location.getLongitude(),
							location.getAddress().address, poi.getName());
					lists.add(myPoi);
				}
				mNearPoiAdapter.notifyDataSetChanged();
			}
			mLocationClient.stop();
		}
	}

	private void updateMapLocation(double latitude, double longitude) {
		// 设定中心点坐标
		LatLng cenpt = new LatLng(latitude, longitude);
		// 定义地图状态
		MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(15)
				.build();
		MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
				.newMapStatus(mMapStatus);
		// 改变地图状态
		mBaiduMap.setMapStatus(mMapStatusUpdate);

	}

	/**
	 * 地图状态改变监听器*
	 */
	private BaiduMap.OnMapStatusChangeListener changeListener = new BaiduMap.OnMapStatusChangeListener() {
		@Override
		public void onMapStatusChangeStart(MapStatus mapStatus) {
		}

		@Override
		public void onMapStatusChange(MapStatus mapStatus) {
		}

		@Override
		public void onMapStatusChangeFinish(MapStatus mapStatus) {
			if (!isClickMoving) {
				LatLng latLng = mapStatus.target;
				requestAddress(latLng);
				// needShowCurrentLocaitonBtn(latLng);
			} else {
				isClickMoving = false;
			}
		}
	};

	/**
	 * 定位,搜索,map相关
	 */
	private GeoCoder mGeoCoder;

	/**
	 * 反编码定位地址
	 * 
	 * @param latLng
	 */
	private void requestAddress(LatLng latLng) {
		if (mGeoCoder == null) {
			mGeoCoder = GeoCoder.newInstance();
			mGeoCoder
					.setOnGetGeoCodeResultListener(mOnGetGeoCoderResultListener);
		}
		mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
	}

	/**
	 * 反编码地址监听器 获取周边3个poi地址信息
	 */
	OnGetGeoCoderResultListener mOnGetGeoCoderResultListener = new OnGetGeoCoderResultListener() {
		@Override
		public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

		}

		@Override
		public void onGetReverseGeoCodeResult(
				ReverseGeoCodeResult reverseGeoCodeResult) {
			if (reverseGeoCodeResult == null
					|| reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
				// 没有找到检索结果
				Toast.makeText(SearchAddressActivity.this, "没有检索到地址",
						Toast.LENGTH_SHORT).show();
				return;
			}
			List<PoiInfo> poiList = reverseGeoCodeResult.getPoiList();
			if (null != poiList && poiList.size() > 0) {
				lists.clear();
				for (int i = 0; i < poiList.size(); i++) {
					PoiInfo poi = poiList.get(i);
					MyPoiInfo myPoi = new MyPoiInfo(poi.location.latitude,
							poi.location.longitude, poi.address, poi.name);
					lists.add(myPoi);
				}
				mNearPoiAdapter.notifyDataSetChanged();
			}
		}
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(position >= 0 && position < mNearPoiAdapter.getCount()){
			myPoiInfo = (MyPoiInfo) mNearPoiAdapter.getItem(position);
			Intent intent = new Intent();
			intent.putExtra("address", myPoiInfo);
			if("end".equals(source)){
				setResult(BaseRailwayActivity.RESULT_MAP_END_ADDRESS, intent);
			}else{
				setResult(BaseRailwayActivity.RESULT_MAP_START_ADDRESS, intent);
			}
			this.finish();
		}
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_search:
			if(searchAddressPop == null){
				searchAddressPop = new SearchAddressPop(this, new SearchCallBack(){

					@Override
					public void setResult(MyPoiInfo address) {
						tv_search_history.setText(searchAddressPop.getInputContent());
						updateMapLocation(address.latitude, address.longitude);
						LatLng latLng = new LatLng(address.latitude, address.longitude);
						requestAddress(latLng);
					}
					
				});
				searchAddressPop.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
				searchAddressPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
			}
			//searchAddressPop.show();
			searchAddressPop.showAsDropDown(mBtLeft);
			break;
		case R.id.image_left:
			this.finish();
		default:
			break;
		}
		
	}

	@Override
	protected void setListeners() {
		// TODO Auto-generated method stub
		
	}
}
